from flask import Blueprint, render_template, request, g, redirect, url_for, flash
from decorators import login_required
from .forms import PhotoUpload, PictureShow
from models import PhotoModel, PictureModel
from exts import db
from sqlalchemy import or_

bp = Blueprint('question_answer', __name__, url_prefix="/")


@bp.route("/")
@login_required
def index():
    photos = PhotoModel.query.order_by(db.text("-create_time")).all()
    pictures = PictureModel.query.order_by(db.text("-create_time")).all()
    return render_template('index.html', photos=photos, pictures=pictures)


@bp.route("photo/upload", methods=["GET", "POST"])
@login_required
def photo_upload():
    if request.method == "GET":
        return render_template("photo_upload.html")
    else:
        form = PhotoUpload(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            photo = PhotoModel(title=title, content=content, author=g.user)
            db.session.add(photo)
            db.session.commit()
            return redirect("/")
        else:
            flash("标题或格式错误！！！")
            return redirect(url_for("question_answer.photo_upload"))


@bp.route("picture/show", methods=["GET", "POST"])
@login_required
def picture_show():
    if request.method == "GET":
        return render_template("picture_show.html")
    else:
        form = PictureShow(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            picture = PictureModel(title=title, content=content, author=g.user)
            db.session.add(picture)
            db.session.commit()
            return redirect("/")
        else:
            flash("标题或格式错误！！！")
            return redirect(url_for("question_answer.picture_show"))


@bp.route("/photo/<int:photo_id>")
def photo_detail(photo_id):
    photo = PhotoModel.query.get(photo_id)
    return render_template("detail.html", photo=photo)

@bp.route("/picture/<int:picture_id>")
def picture_detail(picture_id):
    picture = PictureModel.query.get(picture_id)
    return render_template("picture_detail.html", picture=picture)


@bp.route("/search")
@login_required
def search():
    q = request.args.get("q")
    photos = PhotoModel.query.filter(or_(PhotoModel.title.contains(q),
                                         PhotoModel.content.contains(q))). \
        order_by(db.text("-create_time"))
    return render_template("index.html", photos=photos, q=q)
